<template>
  <div class="app-page">
    <el-table-form ref="form">
      <el-form-item label="人员姓名:">
        <el-input v-model.trim="query.withdrawUser" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="人员编号:">
        <el-input v-model.trim="query.withdrawCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="提瓶充装单号:">
        <el-input v-model.trim="query.fillingCode" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item label="状态:" prop="orderStatus">
        <el-select v-model="query.fillingStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in fillingStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间:" :table-form-merge="1.2">
        <el-date-picker
          v-model="date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          value-format="yyyy-MM-dd"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="单据标签:">
        <el-select v-model="query.fillingLabel" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in fillingLabelList"
            :key="item.value"
            :label="item.keyName"
            :value="item.keyVal"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="提瓶充装机构：">
        <el-tree-select
          v-model="query.operateOrgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
        />
      </el-form-item>
      <el-form-item label="打印状态:">
        <el-select v-model="query.printStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in printStatuslList"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          @click="search"
        >查询</el-button>
        <el-button
          type="default"
          @click="reset"
        >重置</el-button>
      </template>
    </el-table-form>
    <div class="btn">
      <el-button
        v-permission="2"
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >新增</el-button>
      <el-button
        v-permission="3"
        type="primary"
        icon="el-icon-printer"
        @click="printFile"
      >批量打印</el-button>
      <el-button
        v-permission="6"
        type="primary"
        icon="el-icon-document-add"
        @click="typeImport"
      >领瓶导入</el-button>
      <el-button
        v-permission="7"
        type="primary"
        icon="el-icon-edit"
        @click="labelEdit"
      >标签修改</el-button>
      <el-button
        v-permission="8"
        type="primary"
        icon="el-icon-edit"
        @click="ppImport"
      >瓶批导入</el-button>
      <!-- <el-button
        v-permission="10"
        type="primary"
        icon="el-icon-edit"
        @click="ddImport"
      >订单导入</el-button> -->
      <el-button
        v-permission="9"
        type="default"
        icon="el-icon-printer"
        @click="printNoAmount"
      >打印(无金额)</el-button>
    </div>
    <div class="table_Main">
      <lb-table
        ref="lbTable"
        v-el-height-adaptive-table="{ bottomOffset: 10 }"
        v-loading="$loadingPlugin.fetchData"
        class="filling-lbTable"
        border
        highlight-current-row
        element-loading-text="加载中"
        :column="tableData.column"
        :data="tableData.data"
        pagination
        :total="tableData.total"
        :row-class-name="tableRowClassName"
        custom-column
        @fetch="fetchData"
        @selection-change="selectionChange"
        @row-click="rowClick"
      />
      <p class="total">查询条件下合计单数：{{ fillingTotal || 0 }}，合计瓶数：{{ fillingBottleTotal || 0 }}{{ goodsTotal }}</p>
    </div>
    <fillingDetail ref="fillingDetail" :customer-type-map="customerTypeMap" :filling-status-map="fillingStatusMap" @groovePrint="groovePrint" @del="del" @labelEditSingle="labelEditSingle" />
    <add ref="add" :filling-label-list="fillingLabelList" />
    <fillingTypeIn ref="fillingTypeIn" @toTypeIn="toTypeIn" />
    <fillingImport ref="fillingImport" :filling-label-list="fillingLabelList" @toImport="typeIn" />
    <pingpiTypeIn ref="pingpiTypeIn" :filling-label-list="fillingLabelList" @topingpiImport="topingpiImport" />
    <pingpiImport ref="pingpiImport" :customer-type-map="customerTypeMap" :filling-label-list="fillingLabelList" @pingpiTypeIn="pingpiTypeIn" />
    <dingdanTypeIn ref="dingdanTypeIn" :order-status-map="orderStatusMap" :customer-type-map="customerTypeMap" :filling-label-list="fillingLabelList" @todingdanImport="todingdanImport" />
    <dingdanImport ref="dingdanImport" :customer-type-map="customerTypeMap" :filling-label-list="fillingLabelList" @dingdanTypeIn="dingdanTypeIn" />
    <labelEdit ref="labelEdit" :filling-label-list="fillingLabelList" />
  </div>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import fillingDetail from './components/fillingDetail'
  import add from './components/add'
  import { queryMap, fillingCancel, fillingListQuery, fillOrderLabel, getfillingbatchList, getfillingDetail, updateFillingStatus } from '@/api'
  import fillingTypeIn from './components/typeIn'
  import fillingImport from './components/fillingImport'
  import pingpiImport from './components/pingpiImport'
  import pingpiTypeIn from './components/pingpiTypeIn'
  import dingdanImport from './components/dingdanImport'
  import dingdanTypeIn from './components/dingdanTypeIn'
  import getBottle from '@/assets/getBottle.png'
  import bottlePi from '@/assets/bottlePi.png'
  import dingdan from '@/assets/dingdan.png'
  import labelEdit from './components/labelEdit'
  import getTreeData from '@/utils/jsonTree'
  import { mapGetters } from 'vuex'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'

  export default {
    name: 'fillingOrder',
    components: {
      fillingDetail,
      add,
      fillingTypeIn,
      fillingImport,
      pingpiImport,
      pingpiTypeIn,
      dingdanImport,
      dingdanTypeIn,
      labelEdit
    },
    data() {
      return {
        date: [parseTime(new Date(), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')],
        query: {
          fillingCode: '',
          withdrawUser: '',
          withdrawCode: '',
          fillingStatus: 1,
          fillingLabel: '',
          operateOrgSNNo: '',
          printStatus: ''
        },
        fillingStatusMap: [
          {
            desc: '正常',
            value: 1
          },
          {
            desc: '已作废',
            value: 2
          }
        ],
        printStatuslList: [
          {
            desc: '已打印',
            value: 2
          },
          {
            desc: '未打印',
            value: 1
          }
        ],
        currentSelectList: [],
        fillingLabelList: [],
        customerTypeMap: [],
        orderStatusMap: [],
        fillingTotal: 0,
        fillingBottleTotal: 0,
        treeData: [],
        tableData: {
          total: 0,
          data: [],
          column: [
            {
              type: 'selection'
            },
            {
              prop: 'fillingCode',
              width: 160,
              label: '提瓶充装单号',
              className: 'fillingCode',
              render: (h, { row }) => row.invenBillCode
                ? (<div class='fillingCodeImg'>
                 <img src={row.fillingType === 1 ? getBottle : row.fillingType === 2 ? bottlePi : dingdan } alt={''}/>
                 <el-link underline={false} onClick={() => this.openDetail(row)}>{row.fillingCode}</el-link>
              </div>) : (
                <el-link underline={false} onClick={() => this.openDetail(row)}>{row.fillingCode}</el-link>
              )
            },
            {
              prop: 'withdrawUser',
              label: '提瓶人',
              minWidth: 110
            },
            {
              prop: 'withdrawType',
              label: '角色',
              minWidth: 110,
              formatter: row => {
                return row.withdrawType ? row.withdrawType === 1 ? '配送员' : row.withdrawType === 2 ? '用户' : '' : ''
              }
            },
            {
              prop: 'withdrawCode',
              minWidth: 110,
              label: '提瓶人编号'
            },
            {
              prop: 'operateOrgName',
              minWidth: 160,
              label: '提瓶充装机构'
            },
            {
              prop: 'fillingCount',
              width: 100,
              label: '数量'
            },
            {
              prop: 'invenBillCode',
              width: 160,
              label: '关联单号'
            },
            {
              prop: 'printStatus',
              width: 100,
              label: '打印状态',
              render: (h, { row }) =>
              <span>
                {row.printStatus &&
                  formatColumnMap(this.printStatuslList, 'value', row.printStatus, 'desc')}
              </span>
            },
            {
              prop: 'transactTime',
              width: 160,
              label: '创建时间',
              render: (h, { row }) => (
              <span>
                {row.transactTime &&
                  parseTime(row.transactTime, '{y}-{m}-{d} {h}:{i}:{s}')}
              </span>
            )
            },
            {
              prop: 'createUser',
              width: 110,
              label: '创建人'
            },
            {
              prop: 'fillingStatus',
              label: '单据状态',
              minWidth: 110,
              render: (h, { row }) => (
              <span class={row.fillingStatus === 1 ? 'filling-green' : 'filling-red'}>
                {row.fillingStatus &&
                  formatColumnMap(this.fillingStatusMap, 'value', row.fillingStatus, 'desc')}
              </span>
            )
            },
            {
              prop: 'fillingLabelName',
              width: 110,
              label: '单据标签'
            },
            {
              label: '操作',
              align: 'center',
              className: 'action-col',
              fixed: 'right',
              width: 110,
              render: (h, { row, $index }) => {
                return (
                <div>
                  {(row.orderStatus !== -1 && row.orderStatus !== 2) && (
                    <el-link
                    v-permission='4'
                      underline={false}
                      size='mini'
                      onClick={() => this.groovePrint(row, $index)}
                    >
                      打印
                    </el-link>
                  )}
                  {row.fillingStatus === 1 && (
                    <el-link
                    v-permission='5'
                      underline={false}
                      size='mini'
                      type='danger'
                      onClick={() => this.del(row, $index)}
                    >
                      作废
                    </el-link>
                  )}
                </div>
              )
              }
            }
          ]
        },
        goodsTotal: ''
      }
    },
    computed: {
      ...mapGetters(['orgList'])
    },
    async created() {
      this.getfillingLabelList()
      await this.getDetaultTreeData()
    },
    methods: {
      async fetchData({ currentPage, pageSize }) {
        const query = {
          params: { ...this.query },
          currentPage,
          pageSize
        }
        if (this.date && this.date.length > 0) {
          query.params.transactTime = this.date[0] + ' ' + '00:00:00'
          query.params.transactTimeEnd = this.date[1] + ' ' + '23:59:59'
        }
        const res = await fillingListQuery(query)
        this.tableData.data = res.data.rows
        this.tableData.tag = res.data.tag
        this.fillingTotal = res.data.tag && res.data.tag.fillingTotal
        this.fillingBottleTotal = res.data.tag && res.data.tag.fillingBottleTotal
        const t = res.data.tag && res.data.tag.detailList.map(item => (item.specAlias + '：' + item.goodsCount))
        this.goodsTotal = t && t.length > 0 ? '，' + t.join('，') : ''
        if (currentPage === 1) this.tableData.total = res.data.total
      },
      // 获取所属机构数据
      async getDetaultTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async openDetail(row) {
        await this.$refs.fillingDetail.open(row)
      },
      async getfillingLabelList() {
        const parms = { keyFun: 302, keyAttr: 0 }
        const [res, res1, res2] = await Promise.all([fillOrderLabel(parms),
                                                     mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
                                                     mergeAsyncFunc(queryMap, { enumName: 'OrderStatus' })])
        if (res && res.data) {
          this.fillingLabelList = res.data
        }
        this.customerTypeMap = res1.data // 客户类型
        this.orderStatusMap = res2.data.filter((item) => item.value !== 6) // 订单类型(去掉‘已转派’)
      },
      reset() {
        this.query = {
          fillingCode: '',
          withdrawUser: '',
          withdrawCode: '',
          fillingStatus: '',
          fillingLabel: '',
          operateOrgSNNo: '',
          printStatus: ''
        }
        this.date = [parseTime(new Date(), '{y}-{m}-{d}'), parseTime(new Date(), '{y}-{m}-{d}')]
        this.search()
      },
      async add() {
        await this.$refs.add.open()
        this.search()
      },
      selectionChange(e) {
        this.currentSelectList = e
      },
      rowClick(row) {
        const f = this.currentSelectList.find(item => item.fillingCode === row.fillingCode)
        if (f) this.$refs.lbTable.toggleRowSelection(row, false)
        else this.$refs.lbTable.toggleRowSelection(row, true)
      },
      // 批量打印
      async printFile() {
        if (this.currentSelectList && this.currentSelectList.length > 0) {
          const params = this.currentSelectList.map((item) => (item.fillingId))
          const res = await getfillingbatchList(params)
          if (res && res.data) {
            res.data.forEach(item => {
              this.print(item)
            })
          }
        } else {
          this.$message.warning('请先选择数据')
        }
      },
      // 单次打印
      async groovePrint(row) {
        const params = {
          fillingId: row.fillingId
        }
        const res = await getfillingDetail(params)
        if (res && res.data) {
          this.print(res.data, 'single')
        }
      },
      async del(row) {
        this.$confirm('确定作废该充装单吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const params = { fillingId: row.fillingId }
          const res = await fillingCancel(params)
          if (res) {
            this.$message.success('操作成功！')
            this.search()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      },
      async printNoAmount() {
        if (this.currentSelectList && this.currentSelectList.length > 0) {
          const params = this.currentSelectList.map((item) => (item.fillingId))
          const res = await getfillingbatchList(params)
          if (res && res.data) {
            if (res.data.length === 1) {
              this.print(res.data[0], 'single', 'noAmount')
            } else {
              res.data.forEach(item => {
                this.print(item, '', 'noAmount')
              })
            }
          }
        } else {
          this.$message.warning('请先选择数据')
        }
      },
      // 设置行类名
      tableRowClassName({ row }) {
        if (row.fillingStatus === 2) {
          // 说明作废
          return 'deleted-row'
        } else {
          if (row.printStatus === 2) {
            // 已打印
            return 'print-row'
          }
        }
        return ''
      },
      async print(row2, type, val) {
        const row = JSON.parse(JSON.stringify(row2))
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        let temp
        if (val === 'noAmount') {
          temp = cache['41']
        } else {
          temp = cache['40']
        }
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const r = {
          fillingTotalPrice: row.fillingTotalPrice,
          fillingCode: row.fillingCode,
          printDt: parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}'),
          withdrawUser: row.withdrawUser,
          withdrawCode: row.withdrawCode,
          fillingCount: row.fillingCount,
          orgName: row.operateOrgName,
          fillingLabelName: row.fillingLabelName ? row.fillingLabelName : '',
          cardSurplus: row.cardSurplusName ? row.cardSurplusName : '',
          preferentialCount: row.preferentialCountName ? row.preferentialCountName : ''
        }

        const i = row.detailList.map((item) => ({
          goodsName: item.goodsName,
          specAlias: item.specAlias,
          weight: item.weight ? item.weight : '0',
          goodsCount: item.goodsCount
        }))

        let printcmd = {
          cmd: 2,
          title: `正在对充装单${r.fillingCode}进行打印`,
          elements: []
        }
        console.log('r', r)
        printcmd = { ...printcmd, ...temp }
        window.jCPrint.process(printcmd, temp, r, i)
        delete printcmd.els
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
          await updateFillingStatus({ fillingId: row.fillingId })
          if (type && type === 'single') {
            this.search()
          }
        } else {
          this.$message.error('打印未连接')
        }
      },
      // 领瓶导入
      async typeImport() {
        await this.$refs['fillingImport'].open()
        this.search()
      },
      async typeIn() {
        await this.$refs['fillingTypeIn'].open()
        this.search()
      },
      async toTypeIn(selectData) {
        await this.$refs['fillingImport'].open(selectData)
        this.search()
      },
      // 瓶批导入
      async ppImport() {
        await this.$refs['pingpiImport'].open()
        this.search()
      },
      async pingpiTypeIn() {
        await this.$refs['pingpiTypeIn'].open()
        this.search()
      },
      async topingpiImport(selectData) {
        await this.$refs['pingpiImport'].open(selectData)
        this.search()
      },
      // 瓶批导入
      async ddImport() {
        await this.$refs['dingdanImport'].open()
        this.search()
      },
      async dingdanTypeIn() {
        await this.$refs['dingdanTypeIn'].open()
        this.search()
      },
      async todingdanImport(selectData) {
        await this.$refs['dingdanImport'].open(selectData)
        this.search()
      },
      // 标签修改
      async labelEdit() {
        if (this.currentSelectList && this.currentSelectList.length > 0) {
          const params = this.currentSelectList.map((item) => (item.fillingId))
          await this.$refs.labelEdit.open(params)
          this.search()
        } else {
          this.$message.warning('请先选择数据')
        }
      },
      async labelEditSingle(row) {
        await this.$refs.labelEdit.open(row)
        this.search()
        this.$refs.fillingDetail.getDetail()
      }

    }

  }
</script>

<style lang="scss" scoped>
.btn {
  margin-bottom: 10px;
}
/deep/ .el-table tr.deleted-row {
  background: #f59a22;
}
/deep/ .el-table .filling-green {
  color: green;
}
/deep/ .el-table .filling-red {
  color: red;
}
/deep/ .el-table .print-row {
  background: #7cd1f7;
}

.table_Main {
  position: relative;
  .total {
    position: absolute;
    right: 5px;
    bottom: 5px;
    font-size: 16px;
    font-weight: 500;
    color: #F00;
  }
}

.filling-lbTable {
  & /deep/ .el-table .fillingCode {
    padding: 0;
    .fillingCodeImg {
      display: flex;
      margin-left: -9px;
      img {
        width: 30px;
        height: auto;
      }
    }
  }
}
</style>

